<!--
 * @Author: Lijie
 * @Date: 2022-12-08
-->
<template>
  <view class="select-wrap">
    <view
      class="input"
      :class="[!value ? 'placeholder' : '', border ? 'border' : '']"
      :style="'justify-content:' + align"
      @click="showDialog"
    >
      <text>{{ value || placeholder }}</text>
      <text class="arrow cuIcon-right"></text>
    </view>
    <block v-if="show">
      <view class="mask" :class="visible ? 'on' : ''" @click="visible = false"></view>
      <view class="picker-wrap" :class="visible ? 'on' : ''">
        <view class="header">
          <view class="cancel text-gray" @click="visible = false">取消</view>
          <view>{{ placeholder }}</view>
          <view class="ok text-blue" @click="done">确定</view>
        </view>
        <picker-view
          :indicator-style="indicatorStyle"
          :value="dateTime"
          @change="change"
          :immediate-change="true"
          class="picker-view"
        >
          <picker-view-column v-if="formats.includes('YYYY')" style="padding-left: 10rpx">
            <view class="item" v-for="(item, index) in years" :key="index">
              {{ item }}
              <text>年</text>
            </view>
          </picker-view-column>
          <picker-view-column v-if="formats.includes('MM')">
            <view class="item" v-for="(item, index) in months" :key="index">
              {{ item }}
              <text>月</text>
            </view>
          </picker-view-column>
          <picker-view-column v-if="formats.includes('DD')">
            <view class="item" v-for="(item, index) in days" :key="index">
              {{ item }}
              <text>日</text>
            </view>
          </picker-view-column>
          <picker-view-column v-if="formats.includes('HH')">
            <view class="item" v-for="(item, index) in hours" :key="index">
              {{ item }}
              <text>时</text>
            </view>
          </picker-view-column>
          <picker-view-column v-if="formats.includes('mm')">
            <view class="item" v-for="(item, index) in minutes" :key="index">
              {{ item }}
              <text>分</text>
            </view>
          </picker-view-column>
          <picker-view-column v-if="formats.includes('ss')">
            <view class="item" v-for="(item, index) in seconds" :key="index">
              {{ item }}
              <text>秒</text>
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </block>
  </view>
</template>

<script>
import dayjs from 'dayjs';

export default {
  name: 'datePicker',
  props: {
    format: {
      type: String,
      default: 'YYYY-MM-DD HH:mm:ss',
    },
    placeholder: {
      type: String,
      default: '请选择时间',
    },
    value: {
      type: String,
    },
    limit: {
      type: Object,
    },
    align: {
      type: String,
      default: 'space-between',
    },
    border: {
      type: [Boolean, String],
      default: false,
    },
    disabled: {
      type: [Boolean, String],
      default: false,
    },
  },
  data() {
    const date = new Date();
    const years = [];
    const year = String(date.getFullYear());
    const months = [];
    const month = date.getMonth() + 1;
    const days = [];
    const day = date.getDate();
    const hours = [];
    const hour = date.getHours();
    const minutes = [];
    const minite = date.getMinutes();
    const seconds = [];
    const second = date.getSeconds();
    for (
      let i = dayjs().subtract(1, 'year').format('YYYY');
      i <= dayjs().add(10, 'year').format('YYYY');
      i++
    ) {
      years.push(String(i));
    }

    for (let i = 1; i <= 12; i++) {
      months.push(i < 10 ? `0${i}` : `${i}`);
    }

    for (let i = 1; i <= 31; i++) {
      days.push(i < 10 ? `0${i}` : `${i}`);
    }

    for (let i = 0; i <= 23; i++) {
      hours.push(i < 10 ? `0${i}` : `${i}`);
    }

    for (let i = 0; i <= 59; i++) {
      minutes.push(i < 10 ? `0${i}` : `${i}`);
      seconds.push(i < 10 ? `0${i}` : `${i}`);
    }
    return {
      picker: [],
      tempDate: '',
      years,
      year,
      months,
      month,
      days,
      day,
      hours,
      hour,
      minutes,
      minite,
      seconds,
      second,
      show: false,
      visible: false,
      indicatorStyle: `height: 50px;`,
      dateTime: [],
    };
  },
  computed: {
    formats() {
      return this.format.split(/:|\s|-/);
    },
  },
  methods: {
    initDate() {
      let arr = [];
      if (this.value) {
        const T = this.value.split(/:|\s|-/);
        this.formats.forEach((f, i) => {
          switch (f) {
            case 'YYYY':
              arr.push(this.years.indexOf(T[i]));
              break;
            case 'MM':
              arr.push(this.months.indexOf(T[i]));
              break;
            case 'DD':
              arr.push(this.days.indexOf(T[i]));
              break;
            case 'HH':
              arr.push(this.hours.indexOf(T[i]));
              break;
            case 'mm':
              arr.push(this.minutes.indexOf(T[i]));
              break;
            case 'ss':
              arr.push(this.seconds.indexOf(T[i]));
              break;
            default:
          }
        });
      } else {
        arr = [
          this.years.indexOf(this.year),
          this.month - 1,
          this.day - 1,
          this.hour,
          this.minite,
          this.second,
        ];
      }
      this.dateTime = arr;
    },
    showDialog() {
	  if(this.limit && !this.limit.value){
		  uni.showToast({
		    title: this.limit.tip,
		    icon: 'none',
		  });
		  return;
	  }

      this.show = true;
      this.$nextTick(() => {
        this.visible = true;
		this.initDate();
      });
    },
    change(e) {
      const v = e.detail.value;
      this.dateTime = v;
    },
    getDays(y, m) {
      let days;
      const dayArr = [];
      // 当份为二，根据闰年还是非闰年判断天数
      if (m === 2) {
        days = y % 4 === 0 ? 29 : 28;
      } else if (m === 1 || m === 3 || m === 5 || m === 7 || m === 8 || m === 10 || m === 12) {
        // 份为：1,3,5,7,8,10,12 ，为大.则天数为31；
        days = 31;
      } else {
        // 其他份，天数为：30.
        days = 30;
      }
      for (let i = 1; i <= days; i++) {
        if (i < 10) {
          dayArr.push(`0${i}`);
        } else {
          dayArr.push(`${i}`);
        }
      }
      // 输出天数
      return dayArr;
    },
    getDateByPicker(v) {
      const temp = [];
      this.formats.forEach((f, i) => {
        switch (f) {
          case 'YYYY':
            temp.push(this.years[v[i]], '-');
            break;
          case 'MM':
            temp.push(this.months[v[i]], '-');
            break;
          case 'DD':
            temp.push(this.days[v[i]], ' ');
            break;
          case 'HH':
            temp.push(this.hours[v[i]], ':');
            break;
          case 'mm':
            temp.push(this.minutes[v[i]], ':');
            break;
          case 'ss':
            temp.push(this.seconds[v[i]], ':');
            break;
          default:
        }
      });
      this.tempDate = temp.join('').replace(/(^\s*)|((:|\s*)$)/g, '');
    },
    done() {
      this.getDateByPicker(this.dateTime);
      if (this.limit) {
        if (new Date(dayjs(this.tempDate).format()).getTime() <= new Date(dayjs(this.limit.value).format()).getTime()) {
          uni.showToast({
            title: this.limit.tip,
            icon: 'none',
          });
          return;
        }
      }
	  if(this.value !== this.tempDate){
		 this.$emit('change', this.tempDate);  
	  }
      this.$emit('update:value', this.tempDate);
      this.visible = false;
    },
  },
  created() {
    this.initDate();
  },
};
</script>

<style lang="scss" scoped>
.select-wrap {
  flex: 1;
  .placeholder {
    color: #bfbfbf;
    font-size: 28rpx;
  }
  .input {
    display: flex;
    align-items: center;
    height: 60rpx;
    line-height: 60rpx;
    border-radius: 8rpx;
    white-space: no-wrap;
    overflow: hidden;
    text-overflow: ellipsis;
    &.border {
      border: 1rpx solid #dcdfe6;
    }
  }
  .arrow {
    font-size: 28rpx;
    color: #dcdfe6;
    font-size: 30rpx;
    width: 60rpx;
    text-align: center;
  }
}
.mask {
  position: fixed;
  width: 100vw;
  height: 100vh;
  bottom: 0;
  left: 0;
  visibility: hidden;
  z-index: 999998;
  background: rgba(0, 0, 0, 0);
  transition: all 0.3s;
  &.on {
    background: rgba(0, 0, 0, 0.5);
    visibility: visible;
  }
}
.picker-wrap {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 999999;
  width: 100vw;
  border-top-right-radius: 5rpx;
  border-top-left-radius: 5rpx;
  overflow: hidden;
  transform: translateY(100%);
  transition: all 0.15s ease-in-out;
  &.on {
    transform: translateY(0);
  }
  .header {
    display: flex;
    justify-content: space-between;
    height: 100rpx;
    background: #fff;
    line-height: 100rpx;
    padding: 0 30rpx;
    font-size: 30rpx;
    border-bottom: 1rpx solid #f1f1f1;
  }
  .picker-view {
    width: 100vw;
    height: 600rpx;
    background-color: #fff;
    font-size: 38rpx;
  }
  .item {
    height: 50px;
    line-height: 50px;
    align-items: center;
    justify-content: center;
    text-align: center;
    text {
      font-size: 26rpx;
      margin-left: 5rpx;
      color: #333;
    }
  }
}
</style>
